<?php

namespace App\Models\V1;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Lauthz\Facades\Enforcer;
use Lauthz\Models\Rule;

class SysRole extends BaseModel
{
    use HasFactory;
    protected $table="sys_role";
    protected $fillable=['mch_id','title','role_key','sort','state','remark'];

    /**
     * @return string
     */
    public function getStateAttribute()
    {
        return (string) $this->attributes['state'];
    }


    public function getIdentifier($id)
    {
        return "box_admin_roles_".$id;
    }

    /**
     * 获取用户角色
     * @param $roleId
     * @param $id
     */
    public function setRoles($roleId,$id)
    {
        $id = $this->getIdentifier($id);
        $roles = $this->query()->where('state',1)
            ->whereIn('id',$roleId)
            ->get(['id','title']);

        Enforcer::guard('box_admin')->deleteRolesForUser($id);

        foreach ($roles as $value){
            Enforcer::guard('box_admin')->addRoleForUser($id, $value['id'], $value['title']);
        }
        $rule_model=new Rule([],'box_admin');
        $rule_model->refreshCache();
    }

    /**
     * 获取用户角色
     * @param $id
     * @return mixed
     */
    public function getRoles($id,$mch_id=0){
        $id = $this->getIdentifier($id);
        $roles = Enforcer::guard('box_admin')->getRolesForUser($id);
        if(empty($roles)) return [];
        $roles = $this->query()->where('state',1)
            ->whereIn('id',$roles)
            ->get(['id','title']);
        return $roles;
    }

    /**
     * 通过缓存获取用户角色
     * @param $id
     * @return mixed
     */
    public function getRolesFromCache($id,$mch_id=0){
        $id = $this->getIdentifier($id);
        $roles = Enforcer::guard('box_admin')->getRolesForUser($id);
        if(empty($roles)) return [];
        return $roles;
    }

    /**
     * 删除用户所有角色
     * @param $id
     */
    public function delRoles($id,$roleId=[]){
        $id = $this->getIdentifier($id);
        Enforcer::guard('box_admin')->deleteRolesForUser($id);
        $rule_model=new Rule([],'box_admin');
        $rule_model->refreshCache();
    }


}
